var btnAddEvent = null;
var evtText = null;
var evtDate = null;
var evtGroups = null;

$(function() {

	evtText = $("#evtText");
	evtDate = $("#evtDate");
	evtGroups = $("#evtGroups");

	btnAddEvent = $("#btnAddEvent");
	btnAddEvent.bind("click", add_event);

	$("#testBtn").bind("click", testFunc);
	
	// evtDate.datepicker("option", "defaultDate", +1);
	evtDate.datepicker();
	var dt = new Date();
	dt.setDate(dt.getDate() + 1);
	evtDate.datepicker("setDate", dt)
});

VK.init(function() {

	VK.api('groups.get', {
		'uid' : viewer_id,
		'extended' : '1',
		'fields' : 'title'
	}, function(data) {
		// console.log(data);

		var i = 0;
		$.each(data.response, function(key, value) {
			if (i > 0) {
				evtGroups.append($("<option></option>")
						.attr("value", value.gid).text(value.name));
			}
			i++;
		});

	});

});

function add_event(e) {

	var dt = evtDate.datepicker("getDate");
	if (!dt) {
		alert("Укажите дату!");
		return false;
	}
	dt = dt.toRus();
	
	var msg = dt + '\n' + evtText.val();
	var groupId = evtGroups.val();
	wallPost(-groupId, msg)

//	VK.api('groups.getMembers', {
//		'gid' : groupId
//	}, function(data) {
//		$.each(data.response.users, function(key, val) {
//			console.log('add user: ' + val);
//			wallPost(val, msg);
//		});
//	});

	return false;
}

function wallPost(id, msg) {
	VK.api("wall.post", {
		"owner_id" : id,
		"message" : msg
	}, function(data) {
		console.log(data);
	});
}

function testFunc()
{
	var id = $("#testId").val();
	var msg = $("#testMsg").val();
	wallPost(id, msg);
}

function wallPost2(id) {
	title = $("[titleid=" + id + "]").html();
	imglink = $("[imgid=" + id + "]").children("img").attr("src");
	VK.api('photos.getWallUploadServer', {
		gid : '%group_id%'
	}, function(data) {
		if (data.response) {
			$.post('index.php', {
				action : 'upload',
				upload_url : data.response.upload_url,
				imglink : imglink
			}, function(json) {
				VK.api("photos.saveWallPhoto", {
					server : json.server,
					photo : json.photo,
					hash : json.hash,
					gid : '%group_id%'
				}, function(data) {
					VK.api('wall.post', {
						owner_id : '-%group_id%',
						from_group : '1',
						message : title,
						attachments : data.response['0'].id
					}, function(data) {
						if (data.response) {
							$.post("index.php", {
								action : "hide",
								id : id
							});
							window.location.reload();
						}
					});
				});
			}, 'json');

		}
	});
}

function two(dig) {
	return (dig < 10) ? "0" + dig : dig;
}

Date.prototype.toRus = function() {
	return two(this.getDate()) + "." + two(this.getMonth() + 1) + "."
			+ this.getFullYear();
};
